<template>
  <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
    <n-grid-item>
      <n-form :label-width="80" :model="formValue" :rules="rules" ref="formRef">
        <n-form-item label="昵称" path="username">
          <n-input v-model:value="formValue.username" placeholder="请输入昵称" />
        </n-form-item>

        <n-form-item label="手机号" path="phone">
          <n-input placeholder="请输入联系电话" v-model:value="formValue.phone" />
        </n-form-item>

        <n-form-item label="邮箱" path="email">
          <n-input placeholder="请输入邮箱" v-model:value="formValue.email" />
        </n-form-item>

        <n-form-item path="coverUrl" label="头像">
          <BasicUpload
            :action="`${apiUrl}/system/oss/upload`"
            :headers="uploadHeaders"
            :max-number="1"
            name="file"
            @upload-change="coverUploadChange"
            v-model:value="uploadList"
            helpText="文件不超过20MB"
          />
        </n-form-item>

        <!--        <n-form-item label="联系地址" path="address">-->
        <!--          <n-input v-model:value="formValue.address" type="textarea" placeholder="请输入联系地址" />-->
        <!--        </n-form-item>-->

        <div>
          <n-space>
            <n-button type="primary" @click="formSubmit">更新基本信息</n-button>
          </n-space>
        </div>
      </n-form>
    </n-grid-item>
  </n-grid>
</template>

<script lang="ts" setup>
  import { nextTick, onMounted, reactive, ref } from 'vue';
  import { FormItemRule, useMessage } from 'naive-ui';
  import { useGlobSetting } from '@/hooks/setting';
  import { useUserStore } from '@/store/modules/user';
  import { updateUserInfoApi } from '@/api/system/user';

  const userStore = useUserStore();
  const token = userStore.getToken;

  const { apiUrl } = useGlobSetting();
  const uploadList = ref<any[]>([]);
  const uploadHeaders = reactive({
    Authorization: token,
  });

  function coverUploadChange(list: any[]) {
    formValue.value['avatar'] = list.join(',');
  }

  const rules = {
    username: {
      required: true,
      message: '请输入昵称',
      trigger: 'blur',
    },
    avatar: {
      required: true,
      message: '请输入昵称',
      trigger: 'blur',
    },
    phone: {
      required: true,
      trigger: 'blur',
      validator: (rule: FormItemRule, value: string) => {
        return new Promise<void>((resolve, reject) => {
          if (!value) {
            reject(Error('请输入手机号码')); // reject with error message
          } else {
            const reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
            if (reg.test(value)) {
              resolve();
            } else {
              reject(Error('请输入正确的手机号码'));
            }
          }
        });
      },
    },
    email: {
      // required: true,
      trigger: 'blur',
      validator: (rule: FormItemRule, value: string) => {
        return new Promise<void>((resolve, reject) => {
          // if (!value) {
          //   reject(Error('请输入邮箱')); // reject with error message
          // } else {
          const reg = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
          if (reg.test(value)) {
            resolve();
          } else {
            reject(Error('请输入正确的邮箱'));
          }
          // }
        });
      },
    },
  };
  const formRef: any = ref(null);
  const message = useMessage();

  const formValue = ref<any>({
    username: '',
    avatar: '',
    phone: '',
    email: '',
  });

  function formSubmit() {
    formRef.value.validate(async (errors) => {
      if (!errors) {
        try {
          await updateUserInfoApi(formValue.value);
          await userStore.getInfo();
          message.success('更新成功');
        } finally {
          console.log('更新成功');
        }
      } else {
        message.error('请填写完整信息');
      }
    });
  }

  onMounted(() => {
    formValue.value = JSON.parse(JSON.stringify(userStore.getUserInfo));
    uploadList.value = formValue.value.avatar ? [formValue.value.avatar] : [];
  });
</script>
